/**
 * Created by hehe on 2015/7/21.
 */
var fs = require('fs'),
    Q = require('q'),
    DaoFactory = require('../dao'),
    FileDao = DaoFactory.FileDao,
    constants = require('commom').constants;

function FileBiz() {
    this.fileDao = new FileDao();
}

FileBiz.prototype.findFileListByStatus = function(option){
    return this.fileDao.findFileListByStatus(option);
}

FileBiz.prototype.upload = function(option){
    var defferred = Q.defer();
    fs.writeFile(constants.file.basePath + option.fileRename,option.fileData,"base64",function(err,data){
            if(err){
                defferred.reject(err);
            }else{
                defferred.resolve(data);
            }
    });
    return defferred.promise;
}

FileBiz.prototype.insertFile = function (file) {
    return this.fileDao.insertFile(file);
}

FileBiz.prototype.execute = function(option){
    var self = this,defferred = Q.defer();
    self.upload(option).then(function(data){
        return self.insertFile(option);
    },defferred.reject).then(function(data){
        defferred.resolve({fileRename:data.FFileRename,batchID:data._id});
    },defferred.reject);

    return defferred.promise;
}

exports.FileBiz = FileBiz;